﻿using System;
using System.Linq;
using System.Linq.Expressions;
using DapperLambdaSQL.Model;
using DapperLambdaSQL.Model.Exceptions;

namespace DapperLambdaSQL.Utils
{
    /// <summary>
    /// 解析SQL表达式
    /// </summary>
    public static class ParseSql
    {
        /// <summary>
        /// 解析 SQL:SELECT子句表达式
        /// </summary>
        /// <typeparam name="T">数据库实体</typeparam>
        /// <param name="expression">表达式</param>
        /// <returns>fieldName1,fieldName2</returns>
        public static string ParseFileds<T, TElement>(this Expression<Func<T, TElement>> expression)
        {
            var fileds = ParseExpression.Parse(expression);
            string selectFileds;
            if (fileds?.Any() != true)
            {
                selectFileds = SqlKeyWord.FiledAll;
            }
            else if (fileds.Count() == 1)
            {
                selectFileds = fileds.First();
            }
            else
            {
                selectFileds = string.Join(',', fileds);
            }
            return selectFileds;
        }

        /// <summary>
        /// 解析SQL:WHERE子句表达式
        /// </summary>
        /// <typeparam name="T">数据库实体</typeparam>
        /// <param name="expression">条件字段表达式 eg:x => x.Id</param>
        /// <returns>fieldName</returns>
        public static string ParseFiled<T, TElement>(this Expression<Func<T, TElement>> expression)
        {
            var fileds = ParseExpression.Parse(expression);
            if (fileds?.Count() != 1)
            {
                throw new BuildSQLException("表达式只需有且仅有一个字段！");
            }
            return fileds.First();
        }
    }
}
